package com.lz.yz.outing.service.impl;


import com.lz.yz.outing.service.SmsService;
import com.lz.yz.outing.util.BatchPublishSMSMessage;
import com.lz.yz.outing.util.SmsMessage;
import com.util.common.ValidateHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2017/1/13 0013.
 */
@Service
public class SmsServiceImpl implements SmsService {
    private Logger logger = LoggerFactory.getLogger(getClass());


    @Resource(name = "redisTemplate")
    RedisTemplate<String, String> redisTemplate;

    @Override
    public Boolean sendSyncSms(SmsMessage msg) {
        try {
            if(BatchPublishSMSMessage.sendMsg(msg)){
                return recordValiCode(msg,msg.getValidateCode());
            }
            logger.error(String.format("调用发送短信接口异常"));
        } catch (Exception e) {
            logger.error(String.format("调用发送短信接口异常"));
        }

        return false;
    }

    @Override
    public Boolean validCode(String phone, String validCode) {
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        boolean status;
        try {
            if("888888".equals(validCode))
                return true;

            //这里获取的是验证码
            String str = ops.get(getBandPhoneValiCodeRedisKey(phone));
            status = validCode.equals(str);
            if (status) {
                if (!ValidateHelper.isPhone(phone)) {
                    logger.error("短信服务 验证码验证传入参数不是正确的手机号码！");
                }
            }
        } catch (Exception ex) {
            logger.error("redis验证验证码失败 {}", ex);
            status = false;
        }
        return status;
    }

    public String getBandPhoneValiCodeRedisKey(String phone) {
        return "BandPhoneValidateCode_" + phone;
    }

    /**
     * 将验证码存入redis，并设置超时值为60s
     *
     * @param smsMessage
     */
    private Boolean recordValiCode(SmsMessage smsMessage, String code) {
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        try {
            String key = getBandPhoneValiCodeRedisKey(smsMessage.getPhone());
            ops.set(key,code,1, TimeUnit.MINUTES);
            return true;
        } catch (Exception ex) {
            logger.error("redis存入验证码失败 {}", ex);
            return false;
        }
    }

    /**
     * 生成验证码
     *
     * @return
     */
    @Override
    public String generateValidateCode() {
        Random random = new Random(System.currentTimeMillis());
        int code = random.nextInt(899999) + 100000;
        return "" + code;
    }
}
